package com.process.filter;

import com.process.controller.util.Code;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @ClassName: LoginCheckFilter
 * @Author: 殷凡卓
 * @Date: 2023/4/14 22:53
 */

//拦截所有请求
@WebFilter(filterName = "AdminCheckFilter", urlPatterns = "/excel/*")
@Slf4j
@Order(2)
public class BAdminCheckFilter implements Filter {

    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        Map<String, String> map = new HashMap<>();
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1.1获取本次请求的URI
        String requestURI = request.getRequestURI();// /backend/index.html


        String username = (String)request.getAttribute("username");
        Integer identity = (Integer)request.getAttribute("identity");


        //1.2定义不需要处理的请求路径
        String[] urls = new String[]{
                "/login",
                "/company/import_teacher",

//                "/excel/importClass",
//                "/excel/importAccount",
//                "/excel/importPracticalTask",
//                "/excel/import_PracticeCourse",
//                "/excel/importTrainPlan",
//                "/excel/import_Teacher",
//                "/excel/import_Student",
                "/students/upload/**",
                "/excel/**",
                "/upload-image",
                "/preview/**",
                "/upload"
        };

        //2、判断本次请求是否需要处理
        boolean check = check(urls, requestURI);

        //3、如果不需要处理，则直接放行
        if (check) {
            log.info("Admin为{}不需要处理,放行", requestURI);
            filterChain.doFilter(request, response);
            return;
        }


        log.info("Admin权限验证：{}", requestURI);
        System.out.println(username);
        System.out.println(identity);

        if (identity == 4) {

            map.put("code", Code.GET_OK.toString());
            map.put("msg", "Admin认证成功");
            log.info("Admin权限通过{}",requestURI);

            filterChain.doFilter(request, response);
            return;

        } else {
            //token为空的返回
            log.warn("Admin权限失败_认证");

            map.put("code", Code.TOKEN_ERR.toString());
            map.put("msg", "Admin认证失败");
        }
        JSONObject jsonObject = new JSONObject(map);
        servletResponse.setContentType("application/json");
        //设置响应的编码
        servletResponse.setCharacterEncoding("utf-8");
        //响应
        PrintWriter pw = servletResponse.getWriter();
        pw.write(jsonObject.toString());
        pw.flush();
        pw.close();

    }


    /**
     * 路径匹配，检查本次请求是否需要放行
     *
     * @param urls
     * @param requestURI
     * @return
     */
    public boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
